//
//  UIButton+Block.m
//  UIButton+Block
//
//  Created by develop on 15/9/17.
//  Copyright (c) 2015年 songhailiang. All rights reserved.
//

#import "UIButton+Block.h"

@implementation UIButton (Block)
static BOOL _Sort;
static NSString *_tagStr;
static char eventKey;

/**
 *  UIButton添加UIControlEvents事件的block
 *
 *  @param controlEvent 事件
 *  @param action block代码
 */
- (void) handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)action
{
    objc_setAssociatedObject(self, &eventKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(callActionBlock1:) forControlEvents:event];
}

- (void)callActionBlock1:(id)sender {
    ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &eventKey);
    if (block) {
        block();
    }
}


- (void)setSort:(BOOL)Sort {
    NSNumber *t = @(Sort);
    if (Sort)
    {
        [self setImage:[UIImage imageNamed:@"search_sort_up"] forState:UIControlStateSelected];
    }
    else
    {
        [self setImage:[UIImage imageNamed:@"search_sort_down"] forState:UIControlStateSelected];
    }
    
    objc_setAssociatedObject(self, &_Sort, t, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL )Sort {
    // id objc_getAssociatedObject(id object, const void *key)
    NSNumber *t = objc_getAssociatedObject(self, &_Sort);
    return (int)[t integerValue];
}
// 设置背景颜色for state
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}
// 设置颜色
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
@end
